<template>
    <div class="wrap">
           <div class="top"> 小区户型图录入 </div>     
       <van-form @submit="onComplexSub">
            <van-cell-group inset>
                <!-- <van-field
                    v-model="plexArea"
                    name="plexArea"
                    label="所在地区"
                    placeholder="所在地区"
                    :rules="[{ required: true, message: '请填写' }]"
                /> -->
                <van-field name="plexArea" label="城市区域"  :rules="[{ required: true, message: '请选择' }]">
                    <template #input>
                        <van-radio-group v-model="plexArea" direction="horizontal">
                        <van-radio name="北区">北区 </van-radio> <br>
                        <van-radio name="南区">南区 </van-radio> <br>
                        <van-radio name="中区">中区 </van-radio> 
                        </van-radio-group>
                    </template>
                </van-field>

                <van-field
                    v-model="plexName"
                    name="plexName"
                    label="小区名"
                    placeholder="小区名"
                    :rules="[{ required: true, message: '请填写' }]"
                >
                    <template #input>
                      <van-picker
                        title=" "
                        :columns="columns"
                        ref="picker" confirm-button-text=" " cancel-button-text=" "
                        :default-index="2"
                         @change="onPickChange"
                    />
                    </template>              

                    </van-field>
                <van-field
                    v-model="plexBuild"
                    name="plexBuild"
                    label="楼宇座数"
                    placeholder="楼宇座数"
                    :rules="[{ required: true, message: '请填写' }]"
                />
                <van-field name="uploader" label="上传户型图"  :rules="[{ required: true, message: '请上传' }]" >
                    <template #input>
                        <van-uploader :max-size="5000* 1024" v-model="plexPic" :max-count="1" :after-read="afterRead" :before-read="beforeRead" >
                              <template #preview-cover="{ file }">
                            <div class="preview-cover van-ellipsis">{{ file.name }}</div>
                        </template>
                        </van-uploader>

                    </template>
                      
                </van-field>
            </van-cell-group>
            <p style="color:darkgoldenrod"> Tips 图片格式 JPG/PNG，限制上传5M以下大小的图片 </p>
            <div style="margin: 16px auto;width: 50%;">
                <van-button round block type="primary" native-type="submit">
                提 交
                </van-button>
            </div>
        </van-form>
    </div>



</template>

<script setup >
import { ref, onMounted, getCurrentInstance, inject, watch, reactive  } from 'vue';
import { toRaw } from '@vue/reactivity'
import {useRouter, useRoute} from 'vue-router'
import moment from 'moment'
import { Dialog } from 'vant'

const prefix = 'https://6164-adegg-2gzf0s396d911a4a-1252121250.tcb.qcloud.la'
const comPlexArr = {
    '北区': ['天悦星院', '星福尚岭新筑', '越秀滨江盛悦', '万科金域国际', '泮海蓝湾'],
    '南区': ['合景领峰', '合景叠翠峰', '嘉华新都会', '帕佳图双子星', '江悦城', '恒大御景半岛', '朗晴新天地', '越秀天悦文华'],
    '中区': ['东华名岸', '帕佳图六里', '二沙岛', '世纪城圣廷苑']
}
let columns = ref(['杭州', '宁波', '温州', '绍兴', '湖州', '嘉兴', '金华']);
const plexArea = ref('北区');  // 区域
const plexName = ref('');  // 小区名
const comArray = reactive() // 待用小区分类数组
const plexPic = ref([]);   // 图片路径
const plexBuild = ref('')  // 小区座型
const fileObj = ref({})    // 要上传的文件File对象
const picker = ref(null);
const onComplexSub = async(values) => {
      console.log('submit', values, typeof (plexPic.value) );
      let complex = JSON.parse(JSON.stringify(plexPic))
      console.log('sub2', typeof( complex ), fileObj.value )
      let pciUrl = `apartment/${plexArea.value}_${plexName.value}_${ plexBuild.value }.jpg`
    //   /apartment/东华名岸1.jpg
      cloud.uploadFile({
            // 云存储的路径
            cloudPath: `apartment/${plexArea.value}_${plexName.value}_${ plexBuild.value }.jpg`,
            // 需要上传的文件，File 类型
            filePath: fileObj.value
        })
        .then(async(res) => {
            // 返回文件 ID
            console.log('存储新户型图', res)
            alert('上传成功' + JSON.stringify( res.download_url ) )
            await db.collection('housing').add({
                    "district": plexArea.value,
                    "commu": plexName.value,
                    "building": plexBuild.value,
                    "pic": `${prefix}/${pciUrl}`,
                    'isValid': false,
                    "createTime": db.serverDate()  // 服务器时间
                }).then(res=>{
                    console.log('提交新文件户型@@@@', res)
                    plexBuild.value = ''
                    plexPic.value = []
                    alert('录入成功')
            }).catch(err=>{
                alert('录入未成功'+ JSON.stringify( err ))
            })
        }).catch(err=>{
            alert('上传未成功'+ JSON.stringify( err ))
        })

    };

const afterRead = (file) => {
      // 此时可以自行将文件上传至服务器
      console.log('file', file.file);
      fileObj.value = file.file
    };

const beforeRead = (file) => {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png' ) {
        alert('请上传 JPG/PNG 格式图片');
        return false;
      }
      return true;
    };

const onPickChange=(value, index)=>{
    plexName.value = value
    console.log('HHH', plexName.value, index)
}

watch(plexArea, (newValue, oldValue) => { //直接监听 区域变化，联动滑块
	console.log("count改变了", newValue)
    columns.value = comPlexArr[newValue]
    console.log('新书一组', columns.value)
    picker.value.setColumnValues(0, columns.value);
    plexName.value = comPlexArr[newValue][2]
})

onMounted(async()=>{
    // const db = cloud.database();  
    // db.collection("housing")
    //     // .doc("todo-identifiant-aleatoire")
    //     .update({
    //         // 表示将 done 字段置为 true
    //         isValid: true
    //     })
    //     .then((res) => {
    //         console.log(res.data);
    //     });
    columns.value = comPlexArr['北区']
})

const cloud = inject('$cloud')
 const db = cloud.database();  

</script>

<style lang="scss">
    body {
        margin: 0;  /* 如果页面出现垂直滚动条，则加入此行CSS以消除之 */
    }
    .top{
        margin: 7px auto;
        margin-bottom: 16px;
        width: 100%;
        background: lightcyan;
        padding-bottom: 5px;
        padding-top: 5px;
        font-weight: bold;
        font-size: 17px;
    }
    .tree{
        height: 500px !important;
    }
    .titleSlot{
        color: white ;
        font-weight: bold;
        background-color: darkgoldenrod;
        padding: 5px;
        width: 20px;
        font-size: 20px;
    }
    .kklist{
        width: 95%;
        margin: 0px auto;
    }
    .wrap{
        background: #f7f8fa;
        height: 1000px;
    }

    .ktv_item{
        background-color: white;
        position: relative;
        height: 45px;
    }
    .kk_sort {
        position: absolute;
        left: 5px;
        top:5px;
        font-size: 29px;
        color: red;
        font-weight: bold;
    }
    .kk_name{
        font-size: large;
        color: darkred;
        font-weight: bold;
         position: absolute;
        left: 29px;
        top:14px;
    }
    .score_num{
        color: darkgoldenrod;
        font-size: 20px;        
    }
    .kk_score {
            position: absolute;
            left: 99px;
    }
    .sortTitle {
            position: relative;
            left: -100px;
            margin-bottom: 4px;
            top: -10px;
            font-weight: bold;
            font-size: 19px;
    }
    .sortTitleAll{
            position: relative;
            left: -130px;
            margin-bottom: 4px;
            top: -10px;
            font-weight: bold;
            font-size: 19px;   
    }
.preview-cover {
    position: absolute;
    bottom: 0;
    box-sizing: border-box;
    width: 100%;
    padding: 4px;
    color: #fff;
    font-size: 12px;
    text-align: center;
    background: rgba(0, 0, 0, 0.3);
  }
</style>